/**
 * Created by Administrator on 2015/2/1.
 */

var MongoClient = require('mongodb').MongoClient;
var logger = require('./logger');
var Future = require('fibers/future');
var wait = Future.wait;


var mongoDB = null;
var url = "mongodb://ghostopr:pa888888@127.0.0.1:27017/ghost";
MongoClient.connect(url, function (err, db) {
    if (err)logger.error("mongodb init error", err);
    mongoDB = db;
    logger.info("mongodb init~");
});


exports._find = function (collection, query, callback) {
    mongoDB.collection(collection).find(query).toArray(callback);
};

exports.findManySync = function (collection, query) {
    var findWrapper = Future.wrap(this._find);
    var result = findWrapper(collection, query).wait();
    return result;
};

exports.findOneSync = function (collection, query) {
    var wrapper = Future.wrap(this._find);
    var result = wrapper(collection, query).wait();
    if (result.length == 0 || result.length > 1) {
        logger.warn("collection:" + collection + ",query:" + query + " result is null or more than one!")
        return null;
    }
    return result[0];
};


exports._insert = function (collection, obj, options, callback) {
    mongoDB.collection(collection).insert(obj, options, callback);
};

exports.insertSync = function (collection, obj, options) {
    var insertWrapper = Future.wrap(this._insert);
    var result = insertWrapper(collection, obj, options).wait();
    return result;
};


exports._updateOrInsert = function (collection, query, obj, callback) {
    mongoDB.collection(collection).update(query, {$set:obj}, {upsert: true, w: 1}, callback);
}

/**
 * 如果查询失败，将插入obj
 * @param collection
 * @param query
 * @param obj
 * @private
 */
exports.updateOrInsertSync = function (collection, query, obj) {
    var wrapper = Future.wrap(this._updateOrInsert);
    wrapper(collection, query, obj).wait();
}


exports._updateOnly = function (collection, query, obj, callback) {
    mongoDB.collection(collection).update(query, {$set:obj}, {w: 1}, callback);
}

exports.updateOnlySync = function (collection, query, obj) {
    var wrapper = Future.wrap(this._updateOnly);
    wrapper(collection, query, obj).wait();
}